# -*- encoding: utf-8 -*-
"""
File Name: create_zabbix_dedicated_line_monitor_items
Description:
Author : 'lirui'
date: 2024/2/1
Contact: marjey_lee@163.com
Change Activity:
2024/2/1:
"""
import time

import ll
from modules.zabbix_utils.utils.zabbix_client import ZabbixClient


class ZabbixManager:
    def __init__(
            self,
            ip='188.12.26.32',
            port=802,
            username='network',
            password='P@ssw0rd132',
            new_url=True
    ):
        self.client = ZabbixClient(
            ip=ip,
            port=port,
            username=username,
            password=password,
            new_url=new_url
        )

    def get_client(self):
        return self.client

    def _create_host(self, host_name, group_name):
        """

        """
        t = self.client.get_template('group', 'get_groups')
        t['params']['filter']['name'] = group_name
        group_id = self.client.fetch(t)[0]['groupid']
        t = self.client.get_template(
            'host',
            'create_host'
        )
        t['params']['groups'][0]['groupid'] = group_id
        t['params']['host'] = host_name
        self.client.insert(t)

    def create_host(self, host_name, group_name='Applications'):
        host_id = self.get_host_id(host_name)
        if host_id is None:
            self._create_host(host_name, group_name)
            ll.get_logger().info(f'host {host_name} created')
        else:
            ll.get_logger().warning(f'host {host_name} already exists')

    def get_host_id(self, host_name):
        t = self.client.get_template('host', 'get')
        t['params']['filter'] = {'host': [host_name]}
        content = self.client.fetch(t)
        if len(content) == 0:
            return None
        return content[0]['hostid']
